<template>
	<view>
		<u-navbar back-text="返回" title="用户登录"></u-navbar>
		<view style="padding: 48rpx; margin-top: 50rpx;">
			<view>
				<text style="font-weight: 500; font-size: 40rpx;">欢迎来到{{site.name}}</text>
			</view>
			<view style="margin-top: 12rpx;">
				<text style="font-weight: 500; font-size: 24rpx; color: #9d9d9d; ">数字智慧乡村 · 互联网+乡村</text>
			</view>
		</view>

		<view v-if="!userinfo.id" style="padding: 48rpx;">
			<view style="background-color: #e7e7e7;border-radius: 44rpx;">
				<u-field v-model="account"  placeholder="请填写用户名" label-width="0"></u-field>
			</view>
			<view style="background-color: #e7e7e7;border-radius: 44rpx; margin-top: 22rpx;">
				<u-field v-model="password" placeholder="请填写密码" label-width="0" :password="showpassword" :right-icon="showpassword?'eye':'eye-fill'" @right-icon-click="showpassword=!showpassword"></u-field>
			</view>
		</view>
		<view class="login" v-if="!userinfo.id" style="padding:0rpx 48rpx;">
			<u-button type="success" @click="onLogin()" shape="circle" :custom-style="{padding:'46rpx'}">登录</u-button>
		</view>
		<view style="text-align: center; padding: 48rpx;" v-if="!userinfo.id">
			新用户没有账号？<text style="color: #04BE02;" @click="onClickRegister">立即注册</text>
		</view>

		<view class="bottom-side-otherLogin" @click="getWeChatCode" style="text-align: center; margin-top: 260rpx;" v-if="isWeixin">
			<u-divider bg-color="">微信快速登录</u-divider>
			<view style="text-align: center; margin-top: 24rpx;">
				<u-icon name="weixin-circle-fill" color="#04BE02" size="100"></u-icon>
			</view>
		</view>


		<u-toast ref="uToast" />
	</view>

</template>

<script>
	export default {
		data() {
			return {
				showpassword:true,
				account: '',
				password: '',
				userinfo: {},
				isWeixin: false,
				weixin_appid: '',
				token: '',
				site: {},
			}
		},
		onLoad() {
			var that = this;
			this.checkLogin();
			this.isWeixin = this.isWechat()
			//that.userinfo = uni.getStorageSync('userinfo');
			console.log(that.userinfo);
			this.token = that.userinfo.token;
			console.log(this.token);
			if (this.isWeixin) {
				this.checkWeChatCode() //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				this.getAppid();
			}
			uni.request({
				url: this.$unishow + 'api/index/login',
				method: 'GET',
				data: {
					action: 'info'
				},
				success: res => {
					console.log(res);
					that.site = res.data.site;
				},
				fail: () => {},
				complete: () => {}
			});
		},
		methods: {
			onClickRegister(){
				uni.navigateTo({
					url:'/pages/login/register'
				})
			},
			async checkLogin() {
				this.userinfo = uni.getStorageSync('userinfo');
				this.token = this.userinfo.token;
				let res = await this.$api.myRequest({
					url: 'api/index/checklogin',
					header: {
						token: this.token
					}
				});
				console.log(res);
				if (res.data.code == 1) {
					uni.navigateTo({
						url: '/pages/user/user'
					})
				}
			},
			onLogin() {
				var that = this;
				uni.request({
					url: this.$unishow + 'api/index/login',
					method: 'POST',
					data: {
						account: this.account,
						password: this.password,
					},
					success: res => {
						if (res.data.code === 1) {
							that.userinfo = res.data.data.userInfo;
							console.log(that.userinfo);
							try {
								uni.setStorageSync('userinfo', that.userinfo);
								this.token = that.userinfo.token;
							} catch (e) {
								// error
							}
							that.$refs.uToast.show({
								title: '登陆成功',
								callback: function() {
									uni.navigateBack();
								}
							});
						} else {
							that.$refs.uToast.show({
								title: res.data.msg,
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},

			/*微信登录相关  start*/
			//方法：用来判断是否是微信内置的浏览器
			isWechat() {
				return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
			},
			//方法:用来提取code
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
					[, ''
					])[1]
					.replace(/\+/g, '%20')) || null
			},
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				let code = this.getUrlCode('code')
				//uni.showToast({
				//	title: `微信code=${code}`
				//})
				if (code) {
					this.getOpenidAndUserinfo(code)
				}
			},
			//请求微信接口，用来获取code
			getWeChatCode() {
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				let appid = this.weixin_appid;

				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid +
					"&redirect_uri=" +
					local +
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			},
			//把code传递给后台接口，静默登录
			getOpenidAndUserinfo(code) {
				var that = this;
				uni.request({
					url: this.$unishow + 'api/weixin/login',
					method: 'GET',
					data: {
						code: code
					},
					success: res => {
						console.log('getOpenidAndUserinfo');
						console.log(res);
						if (res.data.code === 1) {
							that.userinfo = res.data.data.userinfo;
							try {
								uni.setStorageSync('userinfo', that.userinfo);
								that.token = that.userinfo.token;
								console.log(that.userinfo);
							} catch (e) {
								// error
							}
							that.$refs.uToast.show({
								title: res.data.msg,
								callback: function() {
									uni.navigateBack(2);
								}
							});
						} else {
							that.$refs.uToast.show({
								title: res.data.msg,
							});
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},

			// 获取appid
			async getAppid() {
				let res = await this.$api.myRequest({
					url: 'api/weixin/getappid'
				});
				this.weixin_appid = res.data.data.app_id;
			}
		}
	}
</script>

<style>
	page {
		background-color: #eceef4;
	}

	.login {
		padding: 1em;
	}
</style>
